package com.jingdianjichi.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.jingdianjichi.auth.application.convert.AuthRolePermissionDTOConverter;
import com.jingdianjichi.auth.application.dto.AuthRolePermissionDTO;
import com.jingdianjichi.auth.common.entity.SystemConstants;
import com.jingdianjichi.auth.domain.entity.AuthRolePermissionBO;
import com.jingdianjichi.auth.domain.redis.RedisUtil;
import com.jingdianjichi.auth.domain.service.AuthRolePermissionDomainService;
import com.jingdianjichi.auth.entity.Result;
import com.jingdianjichi.auth.infra.basic.entity.AuthPermission;
import com.jingdianjichi.auth.infra.basic.entity.AuthRolePermission;
import com.jingdianjichi.auth.infra.basic.entity.AuthUserRole;
import com.jingdianjichi.auth.infra.basic.mapper.AuthPermissionDao;
import com.jingdianjichi.auth.infra.basic.mapper.AuthRolePermissionDao;
import com.jingdianjichi.auth.infra.basic.mapper.AuthUserRoleDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限controller
 *
 * @author: ChickenWing
 * @date: 2023/11/2
 */
@RestController
@RequestMapping("/rolePermission/")
@Slf4j
public class RolePermissionController {

    @Resource
    private AuthRolePermissionDomainService authRolePermissionDomainService;
    @Resource
    private  AuthUserRoleDao authUserRoleDao;
    @Resource
    private  AuthRolePermissionDao authRolePermissionDao;
    @Resource
    private  AuthPermissionDao authPermissionDao;
    @Resource
    private  RedisUtil redisUtil;

    /**
     * 新增角色权限关联关系
     */
    @RequestMapping("add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO authRolePermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RolePermissionController.add.dto:{}", JSON.toJSONString(authRolePermissionDTO));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(authRolePermissionDTO.getPermissionIdList()),"权限关联不能为空");
            Preconditions.checkNotNull(authRolePermissionDTO.getRoleId(),"角色不能为空!");
            AuthRolePermissionBO rolePermissionBO = AuthRolePermissionDTOConverter.INSTANCE.convertDTOToBO(authRolePermissionDTO);
            return Result.ok(authRolePermissionDomainService.add(rolePermissionBO));
        } catch (Exception e) {
            log.error("PermissionController.add.error:{}", e.getMessage(), e);
            return Result.fail("新增角色权限失败");
        }
    }


    /**
     * 手动填好表数据，这里对redis进行初始化
     * @param userId
     * @return
     */
    @PostMapping("/init")
    public Result<String> initRBAC (Long userId){
        AuthUserRole authUserRole = new AuthUserRole();
        authUserRole.setUserId(userId);
        List<AuthUserRole> RolesList = authUserRoleDao.queryAllByLimit(authUserRole);
        if (RolesList.size()>=1) {
            //在redis中设置key
            String rolekey = redisUtil.buildKey(SystemConstants.AUTH_ROLE_PREFIX, userId.toString());
            //去重
            RolesList = RolesList.stream().distinct().collect(Collectors.toList());
            redisUtil.set(rolekey, new Gson().toJson(RolesList));
        }
        List<Long> RoleIdList = RolesList.stream().map(AuthUserRole::getRoleId).collect(Collectors.toList());
        //权限id集合
        List<Long> permissionIds = new ArrayList<>();
        for (Long item : RoleIdList) {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setRoleId(item);
            List<AuthRolePermission> authRolePermissions = authRolePermissionDao.queryAllByLimit(authRolePermission);
            List<Long> perimission = authRolePermissions
                    .stream().map(AuthRolePermission::getPermissionId).collect(Collectors.toList());
            if (perimission.size() == 1 && perimission!=null){
                permissionIds.add(perimission.get(0));
            }
            if (perimission.size() >1){
                permissionIds.addAll(perimission);
            }
        }

        if (permissionIds.size()==0){
            return Result.fail("没有权限");
        }
        //获取permission_key
        List<AuthPermission> perimissionList = permissionIds.stream().map(item -> {
            AuthPermission authPermission = authPermissionDao.queryById(item);
            return authPermission;
        }).collect(Collectors.toList());
        //在redis中设置key
        String permissionkey = redisUtil.buildKey(SystemConstants.AUTH_PERMISSION_PREFIX, userId.toString());
        redisUtil.set(permissionkey, new Gson().toJson(perimissionList));
        return Result.ok("RBAC初始化成功");

    }

}
